//
//  XHSayVIewModel.m
//  xinhua_sx
//
//  Created by 党阳阳 on 14-6-9.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//
#import "ReactiveCocoa.h"
#import "XHSayViewModel.h"
#import "AFNetworking.h"


@interface XHSayViewModel()
@property (nonatomic ,strong) NSString *toPeopleString;
@property (nonatomic ,strong) NSString *sendString;



@end
@implementation XHSayViewModel
- (instancetype)init
{
    self =  [super init];
    if (self) {
       
        _toPeopleString = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/goalUserfindAll-%@.html",COUTURYCODE];//复制时替换成 县区code
        _sendString = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/suggestion.html"];
       

    }
    return  self;
}

// 获取对谁说 列表

- (RACSignal *)getGoalUserId
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
      
        [manager GET :_toPeopleString parameters:nil success:^(AFHTTPRequestOperation*operation, id responseObject) {
            
            id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                            options:NSJSONReadingAllowFragments
                                                              error:nil];
            NSLog(@"json = %@",jsonObject);
            [subscriber sendNext:jsonObject];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
            
            [subscriber sendNext:@"获取失败"];
        }];

        return nil;
    }];
}
// 提交

- (RACSignal *)sendWithGoalUserId:(id)goalUserId stype:(id)stype content:(id)content image:(UIImage *)image
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        id uid = [defaults objectForKey:@"UID"];
    
        if (!uid) {
            
            [subscriber sendNext:@"尚未登录"];
        }else{
        
            //?code=045400&frontUserId=用户ID&stype=类型&content=内容&goalUserId=对谁说
            NSString *string = [NSString stringWithFormat:@"code=%@&frontUserId=%@&stype=%@&content=%@&goalUserId=%@",COUTURYCODE,uid,stype,content,goalUserId]; //复制时替换成 县区code
            NSLog(@"string = %@",string);
            NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
            
            NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_sendString]];
            
            [urlRequest setHTTPMethod:@"POST"];
            [urlRequest setTimeoutInterval:20];
            NSData *imageData = nil;
            
            if (image) {
                
                if (UIImagePNGRepresentation(image) == nil) {
                    imageData = UIImageJPEGRepresentation(image, 1);
                 } else {
                     imageData = UIImagePNGRepresentation(image);
                }
                NSInputStream *inputStream = [[NSInputStream alloc] initWithData:imageData];
                [urlRequest setHTTPBodyStream:inputStream];
            }

            [urlRequest setHTTPBody:data];
            
            NSOperationQueue *queue= [[NSOperationQueue alloc] init];
            
            [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                
                if ([data length]>0 && connectionError == nil) {
                   
                    NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithDictionary: [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&connectionError]];
                    NSLog(@"dic = %@",dic);
                    
                    if ([[dic objectForKey:@"result"] isEqual:@"success"]) {
                        [dic setObject:@"    您的留言已经发表成功，正在处理中，请您稍等几分钟，不要重复发言！5秒钟自动返回。" forKey:@"message"];
                        
                        
                    }
                    [subscriber sendNext:dic];
                    
                    
                }else if (connectionError != nil){
                    
                    NSLog(@"%@",connectionError);
                    [subscriber sendNext:@"网络链接失败"];
                }


            }];

        }
        

        
        return nil;
    }];
}

@end
